package com.yueke.gemini.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

/**
 * ip工具类
 * Created by admin on 2017/10/21.
 */
public class IPUtil {

    /**
     * 获取公网ip
     * return String
     * */
    private static String getMyIP() throws IOException {
        InputStream ins = null;
        try {
            URL url = new URL("http://www.ip138.com/ip2city.asp");
            URLConnection con = url.openConnection();
            ins = con.getInputStream();
            InputStreamReader isReader = new InputStreamReader(ins, "GB2312");
            BufferedReader bReader = new BufferedReader(isReader);
            StringBuffer webContent = new StringBuffer();
            String str = null;
            while ((str = bReader.readLine()) != null) {
                webContent.append(str);
            }
            int start = webContent.indexOf("[") + 1;
            int end = webContent.indexOf("]");
            return webContent.substring(start, end);
        } finally {
            if (ins != null) {
                ins.close();
            }
        }
    }

    public static void main(String[] args) {
        try {
            long beginTime = System.currentTimeMillis();
            System.out.println("公网ip："+getMyIP());
            System.out.println("局域网ip："+getMyIPLocal());
            long endTime = System.currentTimeMillis();
            System.out.println(endTime-beginTime);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取本地ip
     * @return
     * @throws IOException
     */
    private static String getMyIPLocal() throws IOException {
        InetAddress ia = InetAddress.getLocalHost();
        return ia.getHostAddress();
    }


    /**根据域名得到ip
     * @param url
     * @return
     */
    public static String getServerIP(String url) {
        try {
            InetAddress myIPaddress = InetAddress.getByName(url);
            String hostAddress = myIPaddress.getHostAddress();
            return hostAddress;
        } catch (UnknownHostException e) {
        }
        return null;
    }


    /**
     * 获取服务器端ip地址
     * @return
     */
    public static String getServerIp() {
        HttpServletRequest request = ActionUtil.getRequest();
        String remoteAddress = request.getRemoteAddr();
        String headerXForwardedFor = request.getHeader("X-Forwarded-For");
        return headerXForwardedFor == null ? remoteAddress : headerXForwardedFor.split(",")[0];
    }

    /**
     * 获取客户端IP地址
     * @return
     */
    public static String getClientIp() {
        HttpServletRequest request = ActionUtil.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个不为 unknown 的才为真实IP
            String[] ips = ip.split(",");
            for (String i : ips) {
                i = i.trim();
                if (!StringUtils.isEmpty(i) && !"unknown".equalsIgnoreCase(i)) {
                    ip = i;
                    break;
                }
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.indexOf(":") > 0) {
            ip = request.getLocalAddr();
        }
        return ip;
    }
}
